import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {User} from '../../../../../domain/User';
import {UserApiService} from '../../../../services/user/user-api.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-user-create',
  templateUrl: './user-create.component.html',
  styleUrls: ['./user-create.component.less']
})
export class UserCreateComponent implements OnInit {

  validateForm: FormGroup;
  user: User = new User();

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
      this.validateForm.controls[ i ].updateValueAndValidity();
    }

    this.createUser();
    console.log(this.user)
  }


  confirmationValidator = (control: FormControl): { [ s: string ]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
  };

  /**
   * 创建用户
   */
  createUser() {
    this.userApi.createUser(this.user).subscribe((response) => {
      if (response.success) {
        console.log(response.data)
        this.router.navigate(['/home/user/list'])
      }
    })
  }

  constructor(private fb: FormBuilder, private userApi: UserApiService, private router: Router) {
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      email            : [ null, [ Validators.email ] ],
      password         : [ null, [ Validators.required ] ],
      checkPassword    : [ null, [ Validators.required, this.confirmationValidator ] ],
      username         : [ null, [ Validators.required ] ],
      gender           : [],
      signature        : [],
      userType         : [],
    });
  }

}
